#include "server.h"
#include "connection.h"
#include <QMetaMethod>
#include <QDebug>

Server::Server(quint32 port, QObject *parent):QObject(parent) {
    mTcpServer = new QTcpServer(this);
    connect(mTcpServer,SIGNAL(newConnection()),
            this, SLOT(onNewConnection()));
    mTcpServer->listen(QHostAddress::Any, port);
    mManager = new qrs::ServicesManager(this);
    mService = new qrs::TvService(mManager);
    connectSignals();
}

void Server::onNewConnection() {
    QTcpSocket *socket = mTcpServer->nextPendingConnection();
    if ( socket == 0 ) {
        return;
    }
    mManager->addDevice(socket);
}

void Server::connectSignals()
{
    connect(mService, SIGNAL(startSlideshow()),
            mService, SLOT(slideshowStarted()));
    connect(mService, SIGNAL(stopSlideshow()),
            mService, SLOT(slideshowStopped()));
    connect(mService, SIGNAL(setSlideDelay(int)),
            mService, SLOT(slideDelayChanged(int)));
    connect(mService, SIGNAL(setSlideAnim(QString)),
            mService, SLOT(slideAnimChanged(QString)));

    connect(mService, SIGNAL(startRunningLine()),
            mService, SLOT(runningLineStarted()));
    connect(mService, SIGNAL(stopRunningLine()),
            mService, SLOT(runningLineStopped()));
    connect(mService, SIGNAL(setRunningText(QString)),
            mService, SLOT(runningLineTextChanged(QString)));
    connect(mService, SIGNAL(setRunningColor(QString)),
            mService, SLOT(runningLineColorChanged(QString)));
    connect(mService, SIGNAL(setRunningSpeed(int)),
            mService, SLOT(runningLineSpeedChanged(int)));

    connect(mService, SIGNAL(startMessage()),
            mService, SLOT(messageStarted()));
    connect(mService, SIGNAL(stopMessage()),
            mService, SLOT(messageStopped()));
    connect(mService, SIGNAL(setMessageText(QString)),
            mService, SLOT(messageTextChanged(QString)));
    connect(mService, SIGNAL(setMessageColor(QString)),
            mService, SLOT(messageColorChanged(QString)));
    connect(mService, SIGNAL(setMessageType(QString)),
            mService, SLOT(messageTypeChanged(QString)));

    connect(mService, SIGNAL(startVideos()),
            mService, SLOT(videosStarted()));
    connect(mService, SIGNAL(stopVideos()),
            mService, SLOT(videosStopped()));

    connect(mService, SIGNAL(setTimeSchedule(int,QString)),
            mService, SLOT(timeScheduleChanged(int,QString)));
}
